const { Wechaty } = require('wechaty');

Wechaty.instance()
    .on('scan', (url, code) => {
        if (!/201|200/.test(String(code))){
            let loginUrl = url.replace(/\/qrcode\//, '/l/');
            require('qrcode-terminal').generate(loginUrl)
        }
        console.log(`Scan QR Code to login: ${code}\n${url}`)
    })
    .on('login',  user => console.log(`User:${user.name()} weixin:${user.weixin()}`))
    .on('message', async function(m){
        const contact = m.from();
        const content = m.content();
        const room = m.room();

        if(room){
            console.log(`Room: ${room.topic()} Contact: ${contact.name()} Content: ${content}`)
        } else{
            console.log(`Contact: ${contact.name()} Content: ${content}`)
        }

        if(m.self()){ //自己
            return
        }
        console.log('=================ID=============');
        const name = contact.obj.alias;
        console.log(name);

        if(/hello/.test(content)){
            m.say("hello how are you")
        }else if(/room/.test(content)){
            let keyroom = await Room.find({topic: "test"});
            if(keyroom){
                await keyroom.add(contact);
                await keyroom.say("welcome!", contact)
            }
        }else if(/out/.test(content)){
            let keyroom = await Room.find({topic: "test"});
            if(keyroom){
                await keyroom.say("Remove from the room", contact);
                await keyroom.del(contact)
            }
        }else{
            /*m.say("现在本人不在，是机器人时间！有事请留言，我看到了一定回复~")*/
        }
    })
    .init();